package com.playball.lottery.frm.yhzx;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.R;
import com.playball.lottery.ApplicationData;
import com.playball.lottery.base.BaseActivity;
import com.playball.lottery.customview.BallDTO;
import com.playball.lottery.customview.ShowTipDialog;
import com.playball.lottery.frm.buyhall.SsqxhActivity;
import com.playball.lottery.frm.buyhall.SsqxhlbActivity;
import com.playball.lottery.nt.GetRequestParams;
import com.playball.lottery.util.Constants;
import com.playball.lottery.util.ConvertJsonToList;
import com.playball.lottery.util.LotConstants;
import com.playball.lottery.util.LotUtil;
import com.playball.lottery.util.PreferencesUtils;


/**
 * 
 * @author sunfanglei
 * @date 2014年3月26日
 */
public class SavedPlanActivity extends BaseActivity implements LotConstants {

	private ListView listView;
	private Handler handler = new Handler();
	
	private LinearLayout linLay;
	private Button btn_Buy;

	SavedPLanAdapter adapter = new SavedPLanAdapter(new ArrayList<Map<String, Object>>());

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.jddsavedplan);
		TextView info = (TextView) findViewById(R.id.top_title_info);
		info.setText("待发起方案");
		TextView back = (TextView) findViewById(R.id.top_title_back);
		back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onKeyDown(KeyEvent.KEYCODE_BACK, null);
			}
		});

		listView = (ListView) findViewById(R.id.listview);
		loadMoreView = getLayoutInflater().inflate(R.layout.loadmore, null);
		loadMoreButton = (Button) loadMoreView.findViewById(R.id.loadMoreButton);
		loadMoreButton.setOnClickListener(new View.OnClickListener() {
        
			public void onClick(View v) {
				loadMoreButton.setText("正在加载中..."); // 设置按钮文字
				loadMoreButton.setEnabled(false);
				handler.postDelayed(new Runnable() {
					public void run() {
						pageNo += 1;
						startDetailThread();
						loadMoreButton.setText("加载更多..."); // 恢复按钮文字
						loadMoreButton.setEnabled(true);
					}
				}, 2000);

			}
		});
        
		linLay=(LinearLayout)findViewById(R.id.linLay);
		btn_Buy=(Button)findViewById(R.id.btn_Buy);
		btn_Buy.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				PreferencesUtils pUtil = new PreferencesUtils(SavedPlanActivity.this, Constants.PREFERENCES_NAME);
				Intent intent = new Intent();
				int ssq_size = pUtil.getInt("ssq_size", 0);
				if (ssq_size != 0) {
					ArrayList<BallDTO> list = new ArrayList<BallDTO>();
					for (int i = 0; i < ssq_size; i++) {
						BallDTO ball = new BallDTO();
						ball.setSsq_ball(pUtil.getString("ssq_ball" + i, ""));
						list.add(ball);
					}
					intent.putExtra("list_ssqdto", list);
					intent.putExtra("AllMoney", pUtil.getInt("ssq_allMoney", 0));
					intent.setClass(SavedPlanActivity.this, SsqxhlbActivity.class);
					Toast.makeText(SavedPlanActivity.this, R.string.this_is_the_last_time_you_save_the_number,
							Toast.LENGTH_SHORT).show();
				} else {
					intent.setClass(SavedPlanActivity.this, SsqxhActivity.class);
				}
				startActivity(intent);
			}
		});
		
		startDetailThread();

	}

	public void onResume() {
		super.onResume();
		
	}

	public void onPause() {
		super.onPause();
		
	}

	private void startDetailThread() {
		AsyncLoader task = new AsyncLoader();
		String[] dyn = new String[2];
		JSONObject paramArr = new JSONObject();
		try {
			// 设置请求所需参数
			paramArr.put("PageNo", pageNo);
			paramArr.put("PageSize", pageSize);
		} catch (JSONException ex) {
			// TODO Auto-generated catch block
			Log.e("error", ex.toString());
		}
		dyn[0] = paramArr.toString();
		dyn[1] = "119";
		task.execute(dyn);
	}

	class SavedPLanAdapter extends BaseAdapter {
		List<Map<String, Object>> listData = new ArrayList<Map<String, Object>>();

		public SavedPLanAdapter(List<Map<String, Object>> listData) {
			this.listData = listData;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return listData.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return listData.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		public void addItem(Map<String, Object> map) {
			listData.add(map);
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			if (convertView == null) {
				convertView = getLayoutInflater().inflate(R.layout.jddsavedplan_list_item, null);
			}
			ImageView lotImg = (ImageView) convertView.findViewById(R.id.saved_plan_lotimg);
			lotImg.setImageResource(LotUtil.getLotIconIDByName(listData.get(position).get("LotteryID").toString()));
			TextView lotName = (TextView) convertView.findViewById(R.id.saved_plan_lotname);
			lotName.setText(listData.get(position).get("LotteryID").toString());
			TextView endtime = (TextView) convertView.findViewById(R.id.saved_plan_endtime);
			endtime.setText(listData.get(position).get("BuyEndTime").toString());
			TextView issueName = (TextView) convertView.findViewById(R.id.saved_plan_issuename);
			issueName.setText(listData.get(position).get("IssueName").toString());
			TextView money = (TextView) convertView.findViewById(R.id.saved_plan_money);
			money.setText(listData.get(position).get("Money").toString());
			TextView status = (TextView) convertView.findViewById(R.id.saved_plan_status);
			final boolean isOvered = Boolean.parseBoolean(listData.get(position).get("IsOverdue").toString());
			if (true == isOvered) {
				status.setText("已过期");
			} else {
				status.setText("发起此方案");
			}
			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (true == isOvered) {
						Toast.makeText(SavedPlanActivity.this, R.string.scheme_has_been_expired, Toast.LENGTH_SHORT)
								.show();
					} else {
						// jump
						String str_lotname = listData.get(position).get("LotteryID").toString();
						if (null != str_lotname
								&& (str_lotname.contains("双色") || str_lotname.contains("大乐")
										|| str_lotname.contains("11选5") || str_lotname.contains("内蒙古")
										|| str_lotname.contains("十一运") || str_lotname.contains("重庆时时彩")
										|| str_lotname.contains("福彩3D") || str_lotname.contains("排列")
										|| str_lotname.contains("七乐彩") || str_lotname.contains("七星彩"))) {
							Intent intent = new Intent(SavedPlanActivity.this, SavedPlanDetailActivity.class);
							intent.putExtra("lotName", listData.get(position).get("LotteryID").toString());
							intent.putExtra("BuyEndTime", listData.get(position).get("BuyEndTime").toString());
							intent.putExtra("IssueName", listData.get(position).get("IssueName").toString());
							intent.putExtra("Money", listData.get(position).get("Money").toString());
							intent.putExtra("SchemeID", listData.get(position).get("SchemeID").toString());
							startActivityForResult(intent, REQ_SAVEDPLANDETAIL_FROM_SAVED_PLAN);
						} else if (null != str_lotname
								&& (str_lotname.contains("竞彩") || str_lotname.contains("胜负彩")
										|| str_lotname.contains("任选九") || str_lotname.contains("单场"))) {
							Toast.makeText(SavedPlanActivity.this, "发起" + str_lotname + "保存方案正在开发中哦",
									Toast.LENGTH_SHORT).show();
						} else {
							Toast.makeText(SavedPlanActivity.this, "发起" + str_lotname + "保存方案正在开发中哦",
									Toast.LENGTH_SHORT).show();

						}
					}
				}
			});
			return convertView;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (requestCode == REQ_SAVEDPLANDETAIL_FROM_SAVED_PLAN) {
			if (resultCode == RESULT_OK) {
				pageNo = 1;
				adapter = new SavedPLanAdapter(new ArrayList<Map<String, Object>>());
				startDetailThread();
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			this.finish();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}

	};

	private ShowTipDialog showdialog = new ShowTipDialog();
	// result返回集
	private List<Map<String, Object>> rData;

	/** 记录总条数 */
	private int intTotalNum;

	// 页号
	private int pageNo = 1;
	// 每页条数
	private int pageSize = 10;
	// 是否有下一页
	private boolean nextPage;

	private View loadMoreView;
	private Button loadMoreButton;

	class AsyncLoader extends AsyncTask<String, Integer, String> {// 继承AsyncTask

		// 1.准备运行
		protected void onPreExecute() {
			showdialog.showDialog(SavedPlanActivity.this);
		}

		// 2.正在后台运行
		@Override
		protected String doInBackground(String... paramsArr) {
			// 处理后台执行的任务，在后台线程执行
			String strResult = null;
			// 获取请求返回值
			String UserID = ApplicationData.getInstance().getUserID();
			strResult = GetRequestParams.getRequestUserIDResult(paramsArr[0], UserID, "119", getApplicationContext());
			// 获取请求返回值
			return strResult;
		}

		// 3.进度更新
		protected void onProgressUpdate(Integer... progress) {
		}

		// 4.完成后台任务
		protected void onPostExecute(String result) {
			if (result != null) {
				try {
					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					// 接下来的就是JSON对象的操作了
					if (Integer.parseInt(js.getString("Code")) == 0) {
						rData = new ArrayList<Map<String, Object>>();
						rData = getData(result);
						
						//初始化listview显示，linlay隐藏
						listView.setVisibility(View.VISIBLE);
						linLay.setVisibility(View.GONE);
						
						showList();
						showdialog.closeDialog();
						if(rData.size()==0)
						{
							//SavedPlanActivity.listview.setVisibility(View.GONE);							
							listView.setVisibility(View.GONE);
							linLay.setVisibility(View.VISIBLE);
						}
					} else {
						Toast.makeText(SavedPlanActivity.this, js.getString("Data"), Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException ex) {
					// 异常处理代码
					Log.e("error", ex.toString());
				} finally {
					showdialog.closeDialog();
				}
			} else {
				Toast.makeText(SavedPlanActivity.this, getString(R.string.problem_01), Toast.LENGTH_LONG).show();
			}
		}

		// 5.完成后操作
		protected void onCancelled() {
		}

	}

	public void showList() {
		// 先删除FooterView
		listView.removeFooterView(loadMoreView);
		int maxPage = (intTotalNum % pageSize == 0) ? (intTotalNum / pageSize) : (intTotalNum / pageSize + 1);
		// System.out.println("maxPage maxPage:"+maxPage+"   pageNo:"+pageNo);
		if (pageNo < maxPage) {
			nextPage = true;
		} else {
			nextPage = false;
		}
		if (nextPage) {
			// System.out.println("add foot");
			listView.addFooterView(loadMoreView);
		} else {
			listView.removeFooterView(loadMoreView);
		}
		if (rData.size() != 0) {
			for (int i = 0; i < rData.size(); i++) {
				adapter.addItem(rData.get(i));
			}
		}
		if (pageNo == 1) {
			listView.setAdapter(adapter);
		}
		
		adapter.notifyDataSetChanged();
	}

	private List<Map<String, Object>> getData(String strResult) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			JSONTokener jsonParser = new JSONTokener(strResult);
			JSONObject js = (JSONObject) jsonParser.nextValue();
			int code = Integer.parseInt(js.getString("Code"));
			if (code <= -1) {
				String msg = js.getString("Data");
				Toast.makeText(SavedPlanActivity.this, msg, Toast.LENGTH_LONG).show();
			} else {
				JSONTokener jsonParser1 = new JSONTokener(strResult);
				JSONObject js1 = (JSONObject) jsonParser1.nextValue();
				if (!"".equals(js1.getString("Data"))) {
					String Count = String.valueOf(ConvertJsonToList.getMap(js1.getString("Data")).get("Count"));
					intTotalNum = Integer.parseInt(Count);
					list = ConvertJsonToList.getList(String.valueOf(ConvertJsonToList.getMap(js1.getString("Data"))
							.get("item")));
				} else {
					// 数据为空时为0
					intTotalNum = 0;
				}
			}
		} catch (JSONException ex) {
			// 异常处理代码
			Log.e("error", ex.toString());
		}

		return list;
	}
}
